# coding=utf-8
from flask import current_app, jsonify, request, g, session
from iHome import db, constants, redis_store
from iHome.response_code import RET
from . import api
from iHome.models import Area, House, Facility, HouseImage
from iHome.utils.commons import login_required
from iHome.utils.image_store import image_store
import json


@api.route('/houses')
def get_house_list():
    # 获取所有房屋信息
    area_id = request.args.get('aid')
    sort_key = request.args.get('sk', 'new')
    page = request.args.get('p')
    try:
        if area_id:
            area_id = int(area_id)
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        # houses=House.query.all()
        houses_query = House.query
        # 根据城区的id获取房屋的信息
        if area_id:
            houses_query = houses_query.filter(House.area_id == area_id)
        if sort_key == 'booking':
            houses_query = houses_query.order_by(House.order_count.desc())
        elif sort_key == 'price-inc':
            houses_query = houses_query.order_by(House.price)
        elif sort_key == 'price-des':
            houses_query = houses_query.order_by(House.price.desc())
        else:
            houses_query = houses_query.order_by(House.create_time.desc())
        # 分页操作
        house_paginate = houses_query.paginate(page, constants.HOUSE_LIST_PAGE_CAPACITY, False)
        # 获取当前页的结果列表
        houses = house_paginate.items
        # houses = houses_query.all()

    except Exception as e:

        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询信息失败')
    houses_dict_li = []
    for house in houses:
        houses_dict_li.append(house.to_basic_dict())
    return jsonify(errno=RET.OK, errmsg='OK', data={'houses': houses_dict_li})


# 获取首页房屋展示信息
@api.route('/houses/index')
def get_houses_index():
    try:
        houses = House.query.order_by(House.create_time.desc()).limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询房屋信息失败')
    houses_dict_li = []
    for house in houses:
        houses_dict_li.append(house.to_basic_dict())
    return jsonify(errno=RET.OK, errmsg='OK', data=houses_dict_li)


@api.route('/house/<int:house_id>')
def get_house_info(house_id):
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询信息失败')
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')
    user_id = session.get('user_id', -1)
    user_id = {
        'user_id': user_id
    }
    # 返回应答
    return jsonify(errno=RET.OK, errmsg='OK', data=house.to_full_dict(), user_id=user_id)


@api.route('/houses/image', methods=['POST'])
def save_house_image():
    house_id = request.form.get('house_id')
    if not house_id:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    file = request.files.get('house_image')
    if not file:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询房屋信息失败')
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')
    try:
        key = image_store(file.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传房屋图片失败')
    house_image = HouseImage()
    house_image.house_id = house_id
    house_image.url = key
    # 判断当前房屋是否有默认的图片，如果没有，进行添加
    if not house.index_image_url:
        house.index_image_url = key
    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存房屋失败')
    # 返回应答
    image_url = constants.QINIU_DOMIN_PREFIX + key
    return jsonify(errno=RET.OK, errmsg='OK', data={'image_url': image_url})


@api.route('/houses', methods=['POST'])
@login_required
def save_new_house():
    # 1. 接收房屋的基本信息并进行参数校验
    req_dict = request.json

    title = req_dict.get('title')
    price = req_dict.get('price')  # 房屋价格
    address = req_dict.get('address')
    area_id = req_dict.get('area_id')
    room_count = req_dict.get('room_count')
    acreage = req_dict.get('acreage')
    unit = req_dict.get('unit')
    capacity = req_dict.get('capacity')
    beds = req_dict.get('beds')
    deposit = req_dict.get('deposit')  # 房屋押金
    min_days = req_dict.get('min_days')
    max_days = req_dict.get('max_days')

    if not all(
            [title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')

    try:
        price = float(price) * 100
        deposit = float(deposit) * 100
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 创建house对象并保存房屋的基本信息
    house = House()
    house.user_id = g.user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days
    facility = req_dict.get('facility')
    try:
        facilities = Facility.query.filter(Facility.id.in_(facility)).all()
        # print facilities
        if facilities:
            house.facilities = facilities
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取房屋信息失败')
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存房屋信息失败')
    return jsonify(errno=RET.OK, errmsg='OK', data={'house_id': house.id})


@api.route('/areas')
def get_areas():
    # 先尝试从redis中获取城区信息
    try:
        area_str = redis_store.get('areas')
        if area_str:
            areas_dict_li = json.loads(area_str)
            return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_li)
    except Exception as e:
        current_app.logger.error(e)
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区失败')

    areas_dict_li = [area.to_dict() for area in areas]
    # 将城区信息设置缓冲
    try:
        redis_store.set('areas', json.dumps(areas_dict_li), constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
    return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_li)
